package com.ld.security.common.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;


public class JsonUtil {

    private static ObjectMapper mapper;

    static {
        mapper=new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    private static ObjectMapper getMapper(String... keys){
        return mapper;
    }

    private static SimpleFilterProvider getFilterProvider(String... keys){
        SimpleBeanPropertyFilter fieldFilter = SimpleBeanPropertyFilter.serializeAllExcept(
                keys);
        SimpleFilterProvider filterProvider = new SimpleFilterProvider()

                .addFilter("fieldFilter", fieldFilter);
        return filterProvider;
    }

    public static String toJson(Object obj,String... keys)  {

        ObjectMapper mapper =getMapper(keys);
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("对象转换异常:"+obj);
        }
    }

    public static <E> E clone(Object val,Class<E> cla,Class<?>... clazz){
        return toObject( toJson(val),cla,clazz);
    }

    public static <T> T toObject(String json,Class<T> cla,Class<?>... clazz) {

        try {
            if(clazz.length == 0){
                return JSON.parseObject(json,cla);
            }else{
                ObjectMapper mapper =getMapper();
                JavaType javaType =  mapper.getTypeFactory().constructParametricType(cla, clazz);

                return mapper.readValue(json,javaType);
            }


        } catch (Exception e) {
          throw  new RuntimeException(e);
        }
    }

    public static <E> E toObject(String json, TypeReference<E> tr){
        E obj = JSON.parseObject(json, tr);
        return obj;
    }




}

